package login

import (
	"api/app/auth/models"
	"api/app/auth/service"
	"api/config/code"
	"api/libs/api"
	"context"
	"gitee.com/dreamwood/ez"
	"gitee.com/dreamwood/ez/server"
)

type LoginApi struct {
	api.BaseApi
}

func init() {
	c := &LoginApi{}
	c.RoutePrefix = "/auth/User"
	c.AddRoute("/login", c.LoginAction)
	c.AddRoute("/logout", c.LogoutAction)
	c.AddRoute("/password", c.PasswordAction)
}

func (c *LoginApi) LoginAction(operation *server.Operation) {
	this := c.TakeOver(operation)
	username := this.Get("username").IsString()
	if username == "" {
		this.ReturnError(code.Error, "请输入账号", "")
		return
	}
	password := operation.Get("password").IsString()
	if password == "" {
		this.ReturnError(code.Error, "请输入密码", "")
		return
	}
	crud := models.NewUserCrud()
	crud.Factory.SetAssociations("Roles")
	find, _ := crud.FindOneBy(ez.M{"account": username}, nil)
	if find.IsDelete {
		this.ReturnError(code.Error, "账号已禁用", "")
		return
	}

	if find.Id == 0 {
		//todo 记录尝试次数
		this.ReturnError(code.Error, "账号错误", "")
		return
	}
	if find.Password != service.GenPass(password, find.Salt) {
		//todo 记录尝试次数

		this.ReturnError(code.Error, "密码错误", "")
		return
	}

	if find.Token == "" || (len(find.Token) > 3 && find.Token[:3] != "ABC") {
		find.Token = service.CreateUserToken(find)
	}
	if this.Try(crud.Factory.Update(find)) {
		return
	}

	//find标识账号信息，
	data := make(map[string]interface{})
	data["account"] = find
	//发出登录事件，需要处理的监听器在JsonData中添加个系统的返回
	ez.DispatchToMany("Login", data, context.TODO())
	//用户信息写入缓存
	service.Login(find)
	this.ReturnSuccess("登录成功", data)
}

func (this *LoginApi) LogoutAction(operation *server.Operation) {

}

func (c *LoginApi) PasswordAction(operation *server.Operation) {
	this := c.TakeOver(operation)
	old := this.Get("old").IsString()
	newP := this.Get("new").IsString()
	token := this.GetAuthToken()
	userCrud := models.NewUserCrud()
	find, e := userCrud.FindOneBy(ez.M{"token": token}, nil)
	if this.Try(e) {
		return
	}
	if find.Id == 0 {
		this.ReturnError(code.ErrorAuth, "登录超时", "")
		return
	}
	if find.Password != old {
		this.ReturnError(code.Error, "密码错误", "")
		return
	}
	find.Password = newP
	if this.Try(userCrud.Factory.Update(find)) {
		return
	}
	this.ReturnSuccess("修改成功", "")
}
